package org.squarecap.apps.eventcompanion.web;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.squarecap.apps.eventcompanion.domain.Congreso;
import org.squarecap.apps.eventcompanion.domain.Participante;
import org.squarecap.apps.eventcompanion.domain.Usuario;
import org.squarecap.apps.eventcompanion.util.EmailSender;

@RequestMapping("/congresoes")
@Controller
@RooWebScaffold(path = "congresoes", formBackingObject = Congreso.class)
public class CongresoController {

	@Autowired
	private EmailSender emailSender;
	
	@RequestMapping(value = "/attend/{id}", produces = "text/html")
	public String attend(
			@PathVariable("id") Long id,
			@RequestParam(value = "username", required = false) String username,
			Model uiModel) {
		Congreso congreso = Congreso.findCongreso(id);
		Participante participante = (Participante) Usuario
				.findUsuariosByEmail(username);
		Set<Participante> participantes = congreso.getParticipantes();
		if (participantes.contains(participante)) {
			uiModel.addAttribute("success", "none");
		} else {
			participantes.add(participante);
			congreso.persist();
			emailSender.sendEmail(
					participante.getEmail(), 
					"Event Companion", 
					"Felicitaciones, se ha inscripto a " + congreso.getTitulo());
			uiModel.addAttribute("success", "true");
		}
		return "attendance";
	}
}
